﻿using Blm.Utils.Extensions;
using Language.Resource;
using Microsoft.Extensions.Localization;
using System;
using System.Threading.Tasks;
using VisionCloud.Core.Model.Sys;
using VisionCloud.Domain.Common;
using VisionCloud.Domain.DtoModel.Sys;
using VisionCloud.Domain.Repository.Interface.Sys;
using VisionCloud.Domain.UnitOfWork;

namespace VisionCloud.Service.Sys
{
    public class MenuService
    {
        public IUnitOfWork UnitOfWork { get; set; }
        public ISysMenuRepository SysMenuRepository { get; set; }
        public IStringLocalizer<ServiceResource> Localizer { get; set; }
        public ISysMenuFuncRepository SysMenuFuncRepository { get; set; }

        #region 菜单

        public async Task<bool> Existed(SysMenuDto model)
        {
            return await SysMenuRepository.AnyAsync(p => p.Name.ToLower() == model.Name.ToLower());
        }

        public async Task<ApiPageResult> GetPage(SysMenuCondition conditon)
        {
            return await SysMenuRepository.GetPage(conditon);
        }

        public async Task CreateMenu(SysMenuDto model, Guid opeId)
        {
            var exists = await Existed(model);
            if (exists == true)
            {
                throw new OperationException(Localizer["YB0220"].Value);
            }
            var entity = model.CopyTo<SysMenu>();
            entity.MenuId = Guid.NewGuid();
            entity.CreatedBy = opeId;
            entity.CreatedDate = DateTime.Now;
            entity.LastUpdatedBy = opeId;
            entity.LastUpdatedDate = DateTime.Now;
            SysMenuRepository.Add(entity);
            await UnitOfWork.SaveChangesAsync();
        }

        public async Task DeleteMenu(Guid menuId, Guid opeId)
        {
            var entity = SysMenuRepository.GetById(menuId);
            if (entity == null)
            {
                throw new OperationException(Localizer["YB0221"].Value);
            }
            SysMenuRepository.Update(t => t.MenuId == menuId, d =>
            {
                d.IsDeleted = true;
                d.MenuId = menuId;
                d.LastUpdatedBy = opeId;
                d.LastUpdatedDate = DateTime.Now;
            });
            await UnitOfWork.SaveChangesAsync();
        }

        public async Task UpdateMenu(SysMenuDto model, Guid opeId)
        {
            var entity = model.CopyTo<SysMenu>();
            entity.LastUpdatedBy = opeId;
            entity.LastUpdatedDate = DateTime.Now;
            SysMenuRepository.Update(entity);
            await UnitOfWork.SaveChangesAsync();
        }

        public async Task<SysMenuDto> FindMenu(SysMenuDto SysMenuDto)
        {
            return await SysMenuRepository.FindSysMenu(SysMenuDto);
        }

        #endregion 菜单
    }
}